<?php
namespace api\modules\v1\controllers;

use Yii;
use api\common\controllers\Controller;
use api\modules\v1\models\LoginForm;
use api\modules\v1\models\LogingzhForm;
use common\records\UserInfo;

class AuthController extends Controller
{
    /**
     * @api {post} /v1/auth/login 登录
     * @apiVersion 1.0.0
     * @apiName login
     * @apiGroup Auth
     *
     * @apiParam {String} username 用户名/邮箱
     * @apiParam {String} password  密码
     *
     */
    public function  actionLogin()
    {
        $model = new LoginForm();
        $model->load(request()->post(), '');

        if ($model->login()) {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            if (empty($user->access_token) || $user->expired_at < time() ) {
                $backupToken = $user->access_token;
                $backupQrcode = $user->qrcode;
                //$user->generateAccessToken();
                $token = Yii::$app->security->generateRandomString();
                $user->access_token = $token;
                $user->expired_at = time() + 60 * 60; //* 24 * 30;
                $content = $user->uid.":".$token;
                $code_name = $user->uid.time().".png";
                $res = self::qrcode($content,$code_name);
                //QRcode::png($content, Yii::getAlias('@root/web/storage/upload/'.$code_name), QR_ECLEVEL_L, 3);
                $user->qrcode =Yii::$app->params['http']."://".$_SERVER['HTTP_HOST'].Yii::$app->params['projectName']."/web/storage/upload/".$code_name."?timestamp=".time();
                
                $user->updated_at = date('Y-m-d H:i:s',time());
                $user->save(false);
            }
            $user_info = array();
            $user_info['uid'] = $user->uid;
            $user_info['access_token'] = $user->access_token;
            $user_info['coin'] = $user->coin;
            $user_info['qrcode'] = $user->qrcode;

            return ['user' => $user_info];
        } else {
            return $model;
        }

    }
    
    public function  actionLogingzh()
    {
        $model = new LogingzhForm();
        $model->load(request()->post(), '');

        if ($model->login()) {
            /**
             * @var User $user
             */
            $user = \Yii::$app->user->identity;
            $uid = $user->uid;
            if (empty($user->access_token) || $user->expired_at < time() ) {
                $token = Yii::$app->security->generateRandomString();
                $user->access_token = $token;
                $user->expired_at = time() + 60 * 60; //* 24 * 30;
                $content = $user->uid.":".$token;
                $code_name = $user->uid.time().".png";
                $res = self::qrcode($content,$code_name);
                //QRcode::png($content, Yii::getAlias('@root/web/storage/upload/'.$code_name), QR_ECLEVEL_L, 3);
                $user->qrcode =Yii::$app->params['http']."://".$_SERVER['HTTP_HOST'].Yii::$app->params['projectName']."/web/storage/upload/".$code_name."?timestamp=".time();
                
                $user->updated_at = date('Y-m-d H:i:s',time());
                $user->save(false);
            }
            $user =  UserInfo::find()->where(['uid'=>$uid])->one();
            $user_info = array();
            $user_info['uid'] = $user->uid;
            $user_info['access_token'] = $user->access_token;
            $user_info['coin'] = $user->coin;
            $user_info['qrcode'] = $user->qrcode;

            return ['user' => $user_info];
        } else {
            return $model;
        }

    }

    public function actionUserinfo()
    {
        if(!array_key_exists("uid",$_GET) || !array_key_exists("access-token",$_GET) )
        {
            $result = array();
            $detail = array();

            $detail['code'] = 400;
            $detail['reason'] = "fields missing";
            $result['result'] = $detail;
            return $result;
        }

        $uid = trim($_GET['uid']);
        $access_token = trim($_GET['access-token']);

        $user = UserInfo::find()->where(['uid'=>$uid,'access_token'=>$access_token])->one();
        if($user == null)
        {
            $result = array();
            $detail = array();

            $detail['code'] = 403;
            $detail['reason'] = "auth failed";
            $result['result'] = $detail;
            return $result;
        }
        $user_info = array();
        $user_info['uid'] = $user->uid;
        $user_info['access_token'] = $user->access_token;
        $user_info['coin'] = $user->coin;
        $user_info['qrcode'] = $user->qrcode;
        $user_info['photo'] = $user->photo;
        $user_info['nick'] = $user->nick;
        $result = array();
        $detail = array();
        $detail['code'] = 200;
        $detail['reason'] = "success";
        $detail['user'] = $user_info;
        $result['result'] = $detail;

        return $result;
    }


    public function  actionLoginout()
    {

        if (\Yii::$app->user->logout()) {
            return [];
        }
    }
    function qrcode($content, $code_name)
    {
        $url = Yii::$app->params['url']['qrcode'];
        $post_data = array();
        $post_data["content"] = $content;
        $post_data["name"] = $code_name;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output=curl_exec($ch);
        curl_close($ch);
        return print_r($output,true);
    }
}
